<template>
  <div class="homebox">
    <img src="@/assets/images/bjd.png" alt="" class="bjd" />
    <Headmain :ymbsid="ymbsid" />
    <!-- 数据概览 -->
    <div class="desboxs">
      <div class="desbox1">
        <div class="bsdiv1">已结束：{{ result.ended }}人</div>
        <div class="bsdiv2">今日：{{ result.ongoing }}人</div>
        <div class="bsdiv3">未开始：{{ result.notStarted }}人</div>
      </div>
    </div>
    <!-- 日期选择 -->
    <div class="date-switcher">
      <div class="tool" @click="handleQuickChange('prev')">
        <img src="@/assets/images/preac.png" alt="" class="active" />
        <img src="@/assets/images/pre.png" alt="" class="normal" />
      </div>
      <span class="date-display" @click="dateselect = true"
        >{{ curYear }}年{{ curMonth + 1 }}月</span
      >
      <div class="tool" @click="handleQuickChange('next')">
        <img src="@/assets/images/nexac.png" alt="" class="active" />
        <img src="@/assets/images/nex.png" alt="" class="normal" />
      </div>
    </div>
    <!-- 显示日期框 -->
    <div class="dateselectbox" v-if="dateselect">
      <icon-close class="closedate" @click="dateselect = false" />
      <div class="dateseletyear">
        <span>{{ curYear }}年</span>
        <div class="dateyearnew"
          ><icon-left
            @click="handleQuickChanges('prev')"
            style="cursor: pointer"
        /></div>
        <div class="dateyearnew"
          ><icon-right
            style="cursor: pointer"
            @click="handleQuickChanges('next')"
        /></div>
      </div>
      <div class="dataseletmont">
        <div
          @click="curMonth = item.value"
          class="dataseletmontitem"
          :class="curMonth == item.value ? 'dataseletmontitemhover' : ''"
          v-for="item in monthOptions"
          :key="item.key"
          >{{ item.value + 1 }}月</div
        >
      </div>
    </div>
    <!--日历排版 -->

    <div class="calendar-tablebox">
      <div class="calendar-grid">
        <div class="calendartop">
          <div v-for="(item, i) in weeks" :key="i" class="calendar-header"
            >周{{ item }}</div
          >
        </div>
        <div class="calendar-body">
          <div v-for="(dates, i) in res" :key="i" class="calendar-row">
            <div
              v-for="(item, index) in dates"
              :key="index"
              class="calendar-cell"
              :class="{
                newbj: item.date > curDate,
                oldbj: item.date < curDate,
                livebj: item.date === curDate,
                notCurMonth: !item.isCurMonth,
                notCurMonths: item.isCurMonths,
                currentDay: item.date === curDate,
                selectDay: selectedDates == item.date,
                rangeSelectd: item.isRangeSelected,
                weekend: item.isWeekend,
              }"
              @click="handleItemClick(item, i, index)"
            >
              <span style="z-index: 9" class="daybs">{{
                new Date(item.date).getDate().toString().padStart(2, '0')
              }}</span>

              <div v-if="item.date < curDate" class="jdrboxs">
                <div class="jdritem">
                  <span class="span1"> 接待人数</span>
                  <span v-if="item.data && item.data.length > 0" class="span2">
                    {{ item.data[0].signNumber }}人
                  </span>
                  <span v-else class="span2">0人</span></div
                >
                <div class="jdritem">
                  <span class="span1"> 未到人数</span>
                  <span v-if="item.data && item.data.length > 0" class="span2">
                    {{ item.data[0].noSignNumber }}人
                  </span>
                  <span v-else class="span2">0人</span>
                  <!--   -->
                </div>
              </div>
              <div
                v-else
                class="jdrbox"
                :class="item.date == curDate ? 'jdrboxlive' : 'jdrboxnew'"
              >
                <span class="span1"> 接待人数</span>
                <span v-if="item.data && item.data.length > 0" class="span2">
                  {{ item.data[0].number }}人
                </span>
                <span v-else class="span2">0人</span>
              </div>
              <div
                class="statusmonth"
                :class="
                  item.date > curDate
                    ? 'new'
                    : item.date < curDate
                    ? 'old'
                    : 'live'
                "
              >
                <img
                  src="@/assets/images/new.png"
                  alt=""
                  class="statusicon"
                  v-if="item.date > curDate"
                />
                <img
                  src="@/assets/images/live.png"
                  alt=""
                  class="statusicon"
                  v-if="item.date == curDate"
                />
                <img
                  src="@/assets/images/old.png"
                  alt=""
                  class="statusicon"
                  v-if="item.date < curDate"
                />
                <span>{{
                  item.date > curDate
                    ? '未开始'
                    : item.date < curDate
                    ? '已结束'
                    : '进行中'
                }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <div class="calendar-tablebox">
      <table class="calendar-table">
        <thead class="calendartop">
          <tr>
            <th v-for="(item, i) in weeks" :key="i" style="text-align: center"
              >周{{ item }}</th
            >
          </tr>
        </thead>
        <tbody>
          <tr v-for="(dates, i) in res" :key="i">
            <td
              class="dfbox"
              v-for="(item, index) in dates"
              :key="index"
              :class="{
                notCurMonth: !item.isCurMonth,
                notCurMonths: item.isCurMonths,
                currentDay: item.date === curDate,
                selectDay: selectedDates == item.date,
                rangeSelectd: item.isRangeSelected,
                weekend: item.isWeekend,
              }"
              @click="handleItemClick(item, i, index)"
            >
              <span style="z-index: 9" class="daybs">{{
                new Date(item.date).getDate().toString().padStart(2, '0')
              }}</span>

              <div v-if="item.date < curDate" class="jdrbox">
                <span class="span1"> 已接待人数：</span>
                <span v-if="item.data && item.data.length > 0" class="span2">
                  {{ item.data[0].number }}人
                    {{ item.data[0].signNumber }}
                </span>
                <span v-else class="span2">0人</span>
              </div>
              <div
                v-else
                class="jdrbox"
                :class="item.date == curDate ? 'jdrboxlive' : 'jdrboxnew'"
              >
                <span class="span1"> 接待人数：</span>
                <span v-if="item.data && item.data.length > 0" class="span2">
                  {{ item.data[0].number }}人
                </span>
                <span v-else class="span2">0人</span>
              </div>
              <div class="" v-if="item.data && item.data.length > 0">
                未到人数：{{ item.data[0].noSignNumber }}
              </div>
              <div
                class="statusmonth"
                :class="
                  item.date > curDate
                    ? 'new'
                    : item.date < curDate
                    ? 'old'
                    : 'live'
                "
              >
                <img
                  src="@/assets/images/new.png"
                  alt=""
                  class="statusicon"
                  v-if="item.date > curDate"
                />
                <img
                  src="@/assets/images/live.png"
                  alt=""
                  class="statusicon"
                  v-if="item.date == curDate"
                />
                <img
                  src="@/assets/images/old.png"
                  alt=""
                  class="statusicon"
                  v-if="item.date < curDate"
                />
                <span>{{
                  item.date > curDate
                    ? '未开始'
                    : item.date < curDate
                    ? '已结束'
                    : '进行中'
                }}</span>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div> -->
  </div>
</template>

<script lang="ts" setup>
  import { Message } from '@arco-design/web-vue';
  import { ref, reactive, computed, watch } from 'vue';
  import Headmain from '../headmain/headmain.vue';
  import { saveRest, restList, monthPlan } from '@/api/rest';
  import {
    getDaysInMonth,
    handleCrateDate,
    handleCreateDatePicker,
    parseTime,
  } from '@/utils/timeindex';
  import useLoading from '@/hooks/loading';
  import { useRouter } from 'vue-router';
  const { loading, setLoading } = useLoading(true);
  // 定义当页面标识
  const ymbsid = ref('2');

  //   当前选中日期
  const router = useRouter();
  const selectedDates = ref([]);
  const handleItemClick = (item, i, j) => {
    selectedDates.value = item.date;

    if (item.date == curDate.value) {
      router.push({
        name: 'home',
      });
    }
    if (item.date < curDate.value) {
      router.push({
        name: 'Schedulingold',
        query: {
          date: item.date, // 使用查询字符串携带参数
        },
      });
    }
    if (item.date > curDate.value) {
      router.push({
        name: 'Schedulingnew',
        query: {
          date: item.date, // 使用查询字符串携带参数
        },
      });
    }
    // console.log(
    //   '当前选中日期',
    //   selectedDates.value,
    //   xfdata.value,
    //   movedate.value
    // );
  };

  // 定义 周一到周天
  const weeks = ref(['一', '二', '三', '四', '五', '六', '日']);
  // 当前年
  const curYear = ref(new Date().getFullYear());
  // 当前月
  const curMonth = ref(new Date().getMonth());
  // 当月总天数
  const days = ref();
  // 当前日期 yyyy-MM-dd 格式，用来匹配是否是当前日期
  const curDate = ref(parseTime(new Date().getTime()));
  // 非当前月的上一月展示的日期
  const prevDays = ref();
  // 非当前月的下一月展示的日期
  const rearDays = ref();
  // 当前月的日期
  const curDays = ref();
  // 总共展示的42个日期
  const showDays = ref();
  // 二维数组
  const res = ref();
  //   每周的开始日
  const startOfWeek = ref(1);

  // 初始化日期
  const handleGetDays = (year, month, startOfWeek) => {
    showDays.value = [];
    //   获取每个月的总天数
    days.value = getDaysInMonth(year, month);
    // 计算每个月的一天
    let firstDayOfWeek = new Date(`${year}-${month + 1}-01`).getDay();

    // 处理周起始日
    const obj = {
      1: '一',
      2: '二',
      3: '三',
      4: '四',
      5: '五',
      6: '六',
      0: '日',
    };
    const firstDayInCN = obj[firstDayOfWeek];

    const index = weeks.value.indexOf(firstDayInCN);

    // console.log(firstDayOfWeek, index);

    if (firstDayOfWeek == 0) {
      // 星期天为0 星期一为1 ，以此类推
      firstDayOfWeek = 7;
    }

    prevDays.value = handleCrateDate(year, month, 1, index + 1, 'prev');
    rearDays.value = handleCrateDate(
      year,
      month,
      1,
      42 - days.value - index,
      'rear'
    );

    curDays.value = handleCrateDate(year, month, 1, days.value, '');

    startDate.value = curDays.value[0].date;
    endDate.value = curDays.value[curDays.value.length - 1].date;
    // console.log('当前月份日期', startDate, endDate);
    // 请求数据
    //
    //请求结束
    showDays.value.unshift(...prevDays.value);

    showDays.value.push(...curDays.value);
    showDays.value.push(...rearDays.value);

    res.value = handleFormatDates(showDays.value);
  };
  const handleFormatDates = (arr: string | any[], size = 7) => {
    // 传入长度42的原数组，最终转换成二维数组
    const arr2 = [];
    for (let i = 0; i < size; i++) {
      const temp = arr.slice(i * size, i * size + size);
      arr2.push(temp);
    }

    return arr2;
  };
  const startDate = ref();
  const endDate = ref();
  handleGetDays(curYear.value, curMonth.value, startOfWeek.value);
  weeks.value.unshift(...weeks.value.splice(startOfWeek.value - 1));

  //   初始化日期结束

  //  查询当前月份排版 详情
  //   请求当月排班表
  const monthPlandata = ref();
  const monthPlanget = (startDate: any, endDate: any) => {
    monthPlan({ startDate: startDate, endDate: endDate }).then((res) => {
      if (res.code == 200) {
        monthPlandata.value = res.data;
        showDays.value.forEach((item: { date: any; data: any }) => {
          const dateKey = item.date; // 获取当前日期（例如 '2024-11-25'）
          // 如果 `monthPlandata.value` 中存在对应的日期数据，则将其合并
          if (monthPlandata.value[dateKey]) {
            item.data = monthPlandata.value[dateKey]; // 合并数据
          }
        });
        result.value = calculatePlanStatus(monthPlandata.value, curDate.value);
      }
    });
  };
  monthPlanget(startDate.value, endDate.value);
  // 数据统计
  const calculatePlanStatus = (monthPlanData, curDates) => {
    // 初始化结果对象
    const result = {
      ended: 0,
      ongoing: 0,
      notStarted: 0,
    };

    // 遍历 monthPlanData
    for (const date in monthPlanData) {
      if (monthPlanData.hasOwnProperty(date)) {
        const plans = monthPlanData[date];
        // 计算当前日期下所有 number 的总和
        const totalNumber = plans.reduce((sum, plan) => sum + plan.number, 0);

        // 比较日期并分类

        if (date < curDates) {
          result.ended += totalNumber;
        } else if (date === curDates) {
          result.ongoing += totalNumber;
        } else {
          result.notStarted += totalNumber;
        }
      }
    }

    return result;
  };

  // 切换日期
  // 切换日期
  const handleQuickChange = (type) => {
    if (type === 'prev') {
      curMonth.value--;

      if (curMonth.value == -1) {
        curMonth.value = 11;
        curYear.value -= 1;
      }
    } else if (type === 'next') {
      curMonth.value++;
      if (curMonth.value == 12) {
        curMonth.value = 0;
        curYear.value += 1;
      }
    }
  };

  // 监听curMonth的变化
  watch(curMonth, (newVal) => {
    handleGetDays(curYear.value, newVal, startOfWeek.value);
    monthPlanget(startDate.value, endDate.value);
  });

  // 监听curYear的变化
  watch(curYear, (newVal) => {
    handleGetDays(newVal, curMonth.value, startOfWeek.value);
    monthPlanget(startDate.value, endDate.value);
  });

  //   初始化年 初始化月列表
  const monthOptions = ref(handleCreateDatePicker().months);
  const yearOptions = ref(handleCreateDatePicker().years);

  // 设置年
  const handleQuickChanges = (type) => {
    if (type === 'prev') {
      curYear.value -= 1;
    } else if (type === 'next') {
      curYear.value += 1;
    }
  };
  const dateselect = ref(false);

  // 定义统计
  const result = ref({
    ongoing: 0,
    ended: 0,
    notStarted: 0,
  });
</script>

<style scoped>
  .calendar-tablebox {
    width: 1630px;
    height: 818px;
    background: #ffffff;
    border-radius: 10px;
    border: 1px solid rgba(0, 0, 0, 0.15);
    overflow: hidden;
    margin: 0 auto;
    margin-top: 80px;
    display: flex;
    flex-direction: column;
  }

  .calendar-grid {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
  }

  .calendartop {
    width: 100.1%;
    display: flex;
    background-color: #ffffff;
    border-right: 1px solid #ececec;
    border-bottom: 1px solid #ececec;
    margin: 0 auto;
  }

  .calendar-header {
    flex: 1;
    height: 69px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    color: #000000;
    border-right: 1px solid #ececec;
  }

  .calendar-body {
    display: flex;
    flex-direction: column;
    overflow: hidden;

    height: 800px;
  }

  .calendar-row {
    display: flex;
  }

  .calendar-cell {
    flex: 1;
    height: 150px;
    cursor: pointer;
    border-right: 1px solid #ececec;
    border-bottom: 1px solid #ececec;
    position: relative;
  }

  .notCurMonth {
    color: #ffffff;
    background-color: #f5f6fa;
    opacity: 0.5;
  }

  .selectDay {
    color: #fff;
    background-color: #409eff;
  }

  .rangeSelectd {
    color: #606266;
    background-color: #dee2e9;
  }

  .weekend {
    color: #f73131;
  }

  .selectbox {
    width: 300px;
    height: 80px;
    display: flex;
    background-color: #fff;
    align-items: center;
    justify-content: center;
  }
  .selectbox .arco-form {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    margin: 50px auto;
  }
  .sxcur {
    font-size: 50px;
    cursor: pointer;
  }
  .selectbox .arco-form-item {
    margin-bottom: 0px;
  }
  .dfbox {
    position: relative;
  }
  .xhbox {
    width: 150px;
    padding: 20px 10px;
    background-color: #fff;
    border: 1px solid #999;
    position: absolute;
    right: 0px;
    z-index: 9;
    display: flex;
    flex-direction: column;
  }
  .xhitem {
    color: #999;
  }
  .daybs {
    position: absolute;
    top: 12px;
    right: 12px;
    font-size: 28px;
    color: #000000;
  }

  .date-switcher {
    position: absolute;
    top: 30px;
    left: 50%;
    transform: translate(-50%, 0);
    display: flex;
    align-items: center;
    gap: 10px;
    font-family: Arial, sans-serif;
    z-index: 999;
  }
  .date-switcher div {
  }
  .date-switcher div img {
    width: 32px;
    height: 32px;
  }
  .date-display {
    font-size: 30px;
    font-weight: 550;
    color: #11565c;
    cursor: pointer;
  }

  .statusmonth {
    border-radius: 6px 6px 6px 6px;
    padding: 7px 10px;
    position: absolute;
    left: 12px;
    top: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .statusicon {
    width: 15px;
    height: 15px;
    margin-right: 7px;
  }
  .statusmonth span {
    margin-top: 1px;
  }
  .old {
    color: #5e676f;
  }
  .new {
    color: #5e8d0a;
  }
  .live {
    color: #197b82;
  }
  .jdrboxs {
    width: 204px;
    height: 88px;
    display: flex;
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translate(-50%, 0);
  }

  .jdritem {
    width: 102px;
    height: 88px;
    background: #e9edf2;
    border-radius: 6px 6px 6px 6px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 0 1px;
  }
  .jdrbox {
    width: 204px;
    height: 88px;
    background: #e9edf2;
    border-radius: 6px 6px 6px 6px;
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translate(-50%, 0);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .jdrbox span {
    display: block;
  }
  .span1 {
    color: #9da5ad;
    font-size: 16px;
  }
  .span2 {
    color: #5e676f;
    font-size: 30px;
  }
  .jdrboxnew {
    background: #e1f2b7;
  }
  .jdrboxnew .span1 {
    color: #5e8d0a;
    font-size: 16px;
  }
  .jdrboxnew .span2 {
    color: #5e8d0a;
    font-size: 30px;
  }

  .jdrboxlive {
    background: #b2e2eb;
  }
  .jdrboxlive .span1 {
    color: #197b82;
    font-size: 16px;
  }
  .jdrboxlive .span2 {
    color: #197b82;
    font-size: 30px;
  }
</style>
